package api

import (
	admindao "TaskAssignmentSystem/internal/admin/dao"
	admin "TaskAssignmentSystem/internal/admin/services"
	"TaskAssignmentSystem/internal/app/dao"
	"TaskAssignmentSystem/internal/app/services"
	"TaskAssignmentSystem/internal/pkg/middleware/handler"
	"TaskAssignmentSystem/pkg/oss"
	"TaskAssignmentSystem/pkg/utils"
	"fmt"
	"github.com/kataras/iris/v12"
	"io/ioutil"
	"time"
)

func QuerySystemNotifyColumnListHandler(ctx iris.Context) {
	var notifyServe admin.SystemNotifyServices
	if res, err := notifyServe.QuerySystemNotifyColumnList(); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(res))
		return
	}
}

type AddSystemNotifyColumnRequest struct {
	Name string `json:"name"` //栏目名
}

func AddSystemNotifyColumnHandler(ctx iris.Context) {
	var RequestParams AddSystemNotifyColumnRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var notifyColumn admindao.SystemNotifyColumn
	notifyColumn.Name = RequestParams.Name
	var notifyServe admindao.Common[admindao.SystemNotifyColumn]
	if err := notifyServe.CreateOneReturnId(&notifyColumn).Error; err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(map[string]interface{}{"id": notifyColumn.Id}))
		return
	}
}

type AddSystemNotifyRequest struct {
	ColumnId        uint   `json:"column_id" validate:"required"` //栏目ID
	Title           string `json:"title" validate:"required"`     //标题
	RelatedContent  string `json:"related_content"`               //关联内容
	Content         string `json:"content" validate:"required"`   //内容
	Sort            uint   `json:"sort"`                          //排序
	Status          uint   `json:"status"`                        //状态(0-不显示,1-显示)
	TopStatus       uint   `json:"top_status"`                    //置顶状态(0-不置顶,1-置顶)
	RecommendStatus uint   `json:"recommend_status"`              //推荐状态(0-不推荐,1-推荐)
}

func AddSystemNotifyHandler(ctx iris.Context) {
	var RequestParams AddSystemNotifyRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var notify admindao.SystemNotify
	notify.ColumnId = RequestParams.ColumnId
	notify.Title = RequestParams.Title
	notify.RelatedContent = RequestParams.RelatedContent
	notify.Content = RequestParams.Content
	notify.Sort = RequestParams.Sort
	notify.Status = RequestParams.Status
	notify.TopStatus = RequestParams.TopStatus
	notify.RecommendStatus = RequestParams.RecommendStatus

	var notifyServe dao.Common[admindao.SystemNotify]
	if err := notifyServe.CreateOne(notify).Error; err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseOK())
		return
	}
}

type ModifySystemNotifyRequest struct {
	Id              uint   `json:"id" validate:"required"`
	ColumnId        uint   `json:"column_id" `       //栏目ID
	Title           string `json:"title"`            //标题
	RelatedContent  string `json:"related_content"`  //关联内容
	Content         string `json:"content"`          //内容
	Sort            string `json:"sort"`             //排序
	Status          string `json:"status"`           //状态(0-不显示,1-显示)
	TopStatus       string `json:"top_status"`       //置顶状态(0-不置顶,1-置顶)
	RecommendStatus string `json:"recommend_status"` //推荐状态(0-不推荐,1-推荐)
}

func ModifySystemNotifyHandler(ctx iris.Context) {
	var RequestParams ModifySystemNotifyRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	/*set := map[string]interface{}{
		"column_id":        RequestParams.ColumnId,
		"title":            RequestParams.Title,
		"related_content":  RequestParams.RelatedContent,
		"content":          RequestParams.Content,
		"sort":             RequestParams.Sort,
		"status":           RequestParams.Status,
		"top_status":       RequestParams.TopStatus,
		"recommend_status": RequestParams.RecommendStatus,
	}*/
	set := map[string]interface{}{}
	if RequestParams.ColumnId > 0 {
		set["column_id"] = RequestParams.ColumnId
	}
	if utils.StringIsNotEmpty(RequestParams.Title) {
		set["title"] = RequestParams.Title
	}
	if utils.StringIsNotEmpty(RequestParams.RelatedContent) {
		set["related_content"] = RequestParams.RelatedContent
	}
	if utils.StringIsNotEmpty(RequestParams.Content) {
		set["content"] = RequestParams.Content
	}
	if utils.StringIsNotEmpty(RequestParams.Sort) {
		set["sort"] = RequestParams.Sort
	}
	if utils.StringIsNotEmpty(RequestParams.Status) {
		set["status"] = RequestParams.Status
	}
	if utils.StringIsNotEmpty(RequestParams.TopStatus) {
		set["top_status"] = RequestParams.TopStatus
	}
	if utils.StringIsNotEmpty(RequestParams.RecommendStatus) {
		set["recommend_status"] = RequestParams.RecommendStatus
	}

	var notifyServe dao.Common[admindao.SystemNotify]
	if err := notifyServe.UpdateOne(RequestParams.Id, set).Error; err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseOK())
		return
	}
}

type QuerySystemNotifyDetailRequest struct {
	Id uint `json:"id" validate:"required"`
}

func QuerySystemNotifyDetailHandler(ctx iris.Context) {
	var RequestParams QuerySystemNotifyDetailRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var notifyServe dao.Common[admindao.SystemNotify]
	if res, err := notifyServe.First(map[string]interface{}{"id": RequestParams.Id}); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		updateMap := map[string]interface{}{}
		updateMap["views"] = res.Views + 1
		notifyServe.UpdateOne(res.Id, updateMap)
		ctx.JSON(utils.Response{Code: iris.StatusOK, Message: "ok", Data: res})
		return
	}
}

type DeleteSystemNotifyDetailRequest struct {
	Ids []uint `json:"ids" validate:"required"`
}

func DeleteSystemNotifyDetailHandler(ctx iris.Context) {
	var RequestParams DeleteSystemNotifyDetailRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var notifyServe dao.Common[admindao.SystemNotify]
	//传了ID删除符合的ID
	if len(RequestParams.Ids) > 0 {
		if err := notifyServe.RemoveUnscopedWhere(map[string]interface{}{"id": RequestParams.Ids}).Error; err != nil {
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
			return
		} else {
			ctx.JSON(utils.ResponseOK())
			return
		}
	} else {
		//没传ID删所有可以删除的
		var canDelIds []uint
		if list, err := notifyServe.FindAll(map[string]interface{}{}); err == nil {
			for _, model := range list {
				canDelIds = append(canDelIds, model.Id)
			}
			if err := notifyServe.RemoveUnscopedWhere(map[string]interface{}{"id": canDelIds}).Error; err != nil {
				ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
				return
			} else {
				ctx.JSON(utils.ResponseOK())
				return
			}
		}
	}
}

type QuerySystemNotifyRequest struct {
	Page     int64  `json:"page" validate:"required"`
	PageSize int64  `json:"page_size" validate:"required"`
	ColumnId string `json:"column_id"`
	Title    string `json:"title"`
}

func QuerySystemNotifyListHandler(ctx iris.Context) {
	var RequestParams QuerySystemNotifyRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var notifyServe admin.SystemNotifyServices
	if total, list, err := notifyServe.QuerySystemNotifyList(RequestParams.ColumnId, RequestParams.Title, RequestParams.Page, RequestParams.PageSize); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseData(iris.Map{"count": total, "list": list}))
		return
	}
}

func UploadPicHandler(ctx iris.Context) {
	_, handle, err := utils.FormFile(ctx, "file")
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	file, err := handle.Open()
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}

	//获取当前时间的月份
	currentMonth := time.Now().In(utils.LocationZone).Format("2006-01")

	//关闭打开文件
	defer file.Close()
	fileByte, err := ioutil.ReadAll(file) //获取上传文件字节流
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	var claims services.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}

	var ossClient oss.BucketClient
	if handle.Filename == "image.jpg" {
		handle.Filename = fmt.Sprintf("%d.jpeg", time.Now().Unix())
	}

	fileName := fmt.Sprintf("task-assign/common/pic/%s/%s", currentMonth, handle.Filename)
	if err := ossClient.UpBytes(fileByte, fileName); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		webPath := fmt.Sprintf("%s/%s", utils.ServerConf.AliOssConf.CallBackHost, fileName)
		if webPath != "" {
			ctx.JSON(utils.ResponseData(webPath))
			return
		}
		/*if err := serve.AdvUpdatePath(advId, webPath); err != nil {
			ctx.JSON(utils.ResponseServerError(err))
			return
		} else {
			ctx.JSON(utils.ResponseData(webPath))
			return
		}*/
	}
}

func UploadFileHandler(ctx iris.Context) {
	_, handle, err := utils.FormFile(ctx, "file")
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	file, err := handle.Open()
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}

	//获取当前时间的月份
	currentMonth := time.Now().In(utils.LocationZone).Format("2006-01")

	//关闭打开文件
	defer file.Close()
	fileByte, err := ioutil.ReadAll(file) //获取上传文件字节流
	if err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	var claims services.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}

	var ossClient oss.BucketClient
	/*if handle.Filename == "image.jpg" {
		handle.Filename = fmt.Sprintf("%d.jpeg", time.Now().Unix())
	}*/

	fileName := fmt.Sprintf("task-assign/common/file/%s/%s", currentMonth, handle.Filename)
	if err := ossClient.UpBytes(fileByte, fileName); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		webPath := fmt.Sprintf("%s/%s", utils.ServerConf.AliOssConf.CallBackHost, fileName)
		if webPath != "" {
			ctx.JSON(utils.ResponseData(webPath))
			return
		}
		/*if err := serve.AdvUpdatePath(advId, webPath); err != nil {
			ctx.JSON(utils.ResponseServerError(err))
			return
		} else {
			ctx.JSON(utils.ResponseData(webPath))
			return
		}*/
	}
}

type DelSystemNotifyColumnRequest struct {
	Id uint `json:"id"`
}

func DelSystemNotifyColumnHandler(ctx iris.Context) {
	var RequestParams DelSystemNotifyColumnRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var notifyDao dao.Common[admindao.SystemNotify]
	if RequestParams.Id > 0 {
		if count, err := notifyDao.Count(map[string]interface{}{"column_id": RequestParams.Id}); err != nil {
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
			return
		} else {
			if count > 0 {
				ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: "该内容栏目已被使用,无法删除!"})
				return
			}
			var notifyColumnDao dao.Common[admindao.SystemNotifyColumn]
			if err := notifyColumnDao.DeleteById(RequestParams.Id).Error; err != nil {
				ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
				return
			} else {
				ctx.JSON(utils.ResponseOK())
				return
			}
		}
	}
}
